import React, { Component } from 'react'
import cs from 'classnames'

import Animate from 'rc-animate'
import { Spin } from 'antd'
import { PullToRefresh } from 'antd-mobile'

import style from './index.less'

// 刷新成功后显示提示的时间
const successDuring = 3 * 1000

export default class App extends Component {
  constructor (props) {
    super(props)

    this.state = {
      visibleStatus: false
    }

    this.statusTimer = null
  }

  componentDidMount () {
    const { onLoad } = this.props

    onLoad && onLoad(document.querySelector(`.${ style['box'] }`))
  }

  componentWillReceiveProps (nextProps) {
    if (
      this.props.refreshing === 1 &&
      nextProps.refreshing  === 2 ||
      this.props.refreshing === 1 &&
      nextProps.refreshing  === -1
    ) {
      clearInterval(this.statusTimer)
      this.statusTimer = null

      this.setState({
        visibleStatus: true,
      }, () => {
        this.statusTimer = setTimeout(() => {
          this.setState({ visibleStatus: false })
        }, successDuring)
      })
    }

    if (
      this.props.refreshing === 1 &&
      nextProps.refreshing  === -1
    ) {
      this.setState({
        visibleStatus: true
      }, () => {
        this.statusTimer = setTimeout(() => {
          this.setState({ visibleStatus: false })
        }, successDuring)
      })
    }
  }

  componentWillUnmount () {
    clearTimeout(this.statusTimer)
    this.statusTimer = null
  }

  render () {
    const {
      className,
      children,
      showRefreshingSuccess = true,
      refreshing,

      refreshingText = '刷新中',
      activateText = '松开下拉刷新',
      deactivateText = '下拉可以刷新',
      finishText = '刷新成功',

      onLoad,


      ...rest
    } = this.props

    const {
      visibleStatus
    } = this.state

    let classString = cs(style['box'], className)

    return (
      <PullToRefresh
        indicator = {
          {
            activate: activateText,
            deactivate: deactivateText,
            finish: finishText,
            release: (
              <div className = { style['indicator'] }>
                <Spin />
                <div className = { style['indicator-title'] }>{ refreshingText }</div>
              </div>
            )
          }
        }

        refreshing = { refreshing === 1 }

        { ...rest }

        distanceToRefresh = { 60 }

        className = { classString }
      >
        <Animate transitionName = 'scale'>
          {
            visibleStatus && showRefreshingSuccess ?
              <div
                className = {
                  cs(style['alert'], {
                    [style['alert-fail']]: refreshing === -1
                  })
                }
              >
                <span>
                  { refreshing === 2 ? '刷新成功' : '' }
                  { refreshing === -1 ? '刷新失败' : '' }
                </span>
              </div> :
              null
          }
        </Animate>
        { children }
      </PullToRefresh>
    )
  }
}
